package com.northpool.operator.common.xml;

import cn.hutool.core.util.XmlUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import javax.xml.xpath.XPathConstants;

@OperatorInfo(
        ref = "XmlSetOperator",
        name = "XML操作",
        description = "根据XPath表达式设置XML节点值"
)
@OutputParams({
        @OutputParam(ref = "execResult", name = "修改后的XML字符串", type = TypeEnum.STRING)
})
public class XmlSetOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "XMLStr", name = "XML字符串", desc = "XML文本", type = TypeEnum.STRING, required = true, value = ""),
            @InputParam(ref = "xpath", name = "XPath表达式", desc = "XPath表达式", type = TypeEnum.STRING, required = true, value = ""),
            @InputParam(ref = "value", name = "新值", desc = "要设置的新值", type = TypeEnum.STRING, required = true, value = "")
    })
    public XmlSetOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(XmlSetOperator.class,
                TestParamBuilder.aBuilder()
                        .param("XMLStr", "<?xml version=\"1.0\" encoding=\"utf-8\"?><returnsms><returnstatus>Success（成功）</returnstatus><message>ok</message><remainpoint>1490</remainpoint><taskID>885</taskID><successCounts>1</successCounts></returnsms>")
                        .param("xpath", "//returnsms/message")
                        .param("value", "newmessage")
                        .build()
        );
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String xmlStr = paramTool.getStr("XMLStr");
        String xpath = paramTool.getStr("xpath");
        String value = paramTool.getStr("value");

        Document docResult = XmlUtil.readXML(xmlStr);
        Node node = (Node) XmlUtil.getByXPath(xpath, docResult, XPathConstants.NODE);

        if (node != null) {
            node.setTextContent(value);
        } else {
            throw new RuntimeException("未找到匹配的节点: " + xpath);
        }

        String execResult = XmlUtil.toStr(docResult);
        XmlUtil.escape(execResult);
        this.result("execResult", execResult);
    }
}